import yaml from "js-yaml";
import fs from "node:fs";
import { resolve } from "node:path";

/**
 * 解析 yaml 文件
 * @param filepath - 文件绝对路径 path.resolve()
 * @returns {Object} js 对象
 */
export const resolveYAML = (filepath: string) => {
    try {
        return yaml.load(fs.readFileSync(resolve(filepath), "utf8")) as Record<string, any>;
    } catch (e) {
        throw new Error(`Error loading ${filepath}:\n${e}`);
    }
};

/**
 * 解析 json 文件
 * @param filepath - 文件路径
 * @returns {Object}
 */
export const resolveJSON = (filepath: string) => {
    try {
        const doc = yaml.load(fs.readFileSync(resolve(filepath), "utf8"), { json: true });
        return doc;
    } catch (e) {
        throw new Error(`Error loading ${filepath}:\n${e}`);
    }
};
